package com.tbvtc.agriculturalcreditchainserver2025.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.tbvtc.agriculturalcreditchainserver2025.comment.iot.Enm.LED;
import com.tbvtc.agriculturalcreditchainserver2025.comment.iot.IoTAPI;
import com.tbvtc.agriculturalcreditchainserver2025.constant.RedisConstant;
import com.tbvtc.agriculturalcreditchainserver2025.service.IoTApiService;
import com.tbvtc.agriculturalcreditchainserver2025.utils.Pest.PestConstant;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class IoTApiServiceImpl implements IoTApiService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public void iotFire() {

    }

    @Override
    public void ioFenControl(Boolean isOpen, String token) {
        IoTAPI iotAPI = new IoTAPI();
        String res = iotAPI.setFanData(isOpen);
        System.out.println(res);
    }

    @Override
    public void ioLightControl(LED type, Boolean isOpen, String token) {
        IoTAPI iotAPI = new IoTAPI();
        String s = iotAPI.setLedData(type, isOpen);
        System.out.println(s);
    }

    @Override
    public String smartSockets(String isOpen) {
        WebClient webClient = WebClient.create("http://manage.iot.smart-bird.cn");

        Mono<String> stringMono = webClient.post()
                .uri("/api/geek-iot/device/pub")
                .header("Authorization", "bearer " + getSmartSocketsToken())
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue("{\n" +
                        "    \"clientId\": \"8cce4e516271\",\n" +
                        "    \"cmd\": \"{\\\"type\\\":\\\"event\\\",\\\"key\\\":"+isOpen+"}\"\n" +
                        "}")
                .retrieve()
                .bodyToMono(String.class);
        return stringMono.block();
    }
    public String getSmartSocketsToken() {
        // 创建 WebClient 实例，指定基础地址
        String token = stringRedisTemplate.opsForValue().get(RedisConstant.SMART_SOCKETS_TOKEN);
        if (token == null) {
            WebClient webClient = WebClient.create("http://manage.iot.smart-bird.cn");

            // 定义请求体的 JSON 内容
            String requestBody = "{\"username\": \"15299361189\", \"password\": \"Azathoth123456\"}";

            // 发起 POST 请求并处理响应
            Mono<String> stringMono = webClient.post()
                    .uri("/api/geek-iot/login")
                    .contentType(MediaType.APPLICATION_JSON)
                    .bodyValue(requestBody)
                    .retrieve()
                    .bodyToMono(String.class);
            JSONObject jsonObject = JSONObject.parseObject(stringMono.block());
            // 检查请求是否成功

            // 获取嵌套的data对象中的access_token
            JSONObject dataObject = jsonObject.getJSONObject("data");

            String smartToken = dataObject.getString("access_token");
            stringRedisTemplate.opsForValue().set(RedisConstant.SMART_SOCKETS_TOKEN, smartToken, 30, TimeUnit.MINUTES);
            return smartToken;
        }
        return token;
    }
}
